package com.doit.spark.day06

/**
 * @DATE 2022/1/9/11:07
 * @Author MDK
 * @Version 2021.2.2
 * */
object IpUtils {

  def ipToLong(ip: String): Long = {
    val fragments = ip.split( "\\." )
    var ipNum = 0L
    for (i <- 0 until fragments.length){
      ipNum =  fragments(i).toLong | ipNum << 8L
    }
    ipNum
  }

  def binarySearch(ipRules:Array[IpRuleBean], ip:String): Int ={
    val longIP = ipToLong(ip)
    var startIndex = 0
    var endIndex = ipRules.length-1
    while (startIndex <= endIndex){
      var mid = (startIndex + endIndex)/2
      val bean = ipRules(mid)
      if(longIP < bean.startIP){
        endIndex = mid - 1
      }else if (longIP > bean.endIp){
        startIndex =  mid + 1
      }else {
        return mid
      }
    }
    -1
  }
}
